const router = require('koa-router')();
const query = require('../db/index');


//添加教室号

router.post('/create',async (ctx) =>{
    let {classNum} = ctx.request.body;
    if(classNum){
        //1.排重
        let target = await query('select * from classnum where name=?',[classNum]);
        if(target.length){
            ctx.body = {
                code:4,
                msg:'此教室号已存在'
            }
        }else{
            //容错
            try{
                await query('insert into classnum (name) values (?)',[classNum]);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//教室号删除
router.delete('/delete',async (ctx) => {
    let {id} = ctx.query;
    if(id){
        try{
            await query('delete from classnum where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除教室号成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//查询教室号
router.get('/index',async (ctx) => {
    let list = await query('select * from classnum');
    ctx.body = {
        code:1,
        data:list
    }
})


module.exports = router